package com.phuc.app.vuivui.sqlite;

import java.util.ArrayList;

import com.phuc.app.vuivui.ReadingActivity;
import com.phuc.app.vuivui.utils.Constants;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class TBL_STORY_dao {

	public static ArrayList<Integer> getAllIdByType(int type) {
		ArrayList<Integer> listId = new ArrayList<Integer>();
		int count;
		String sqlScript = "SELECT ID FROM TBL_STORY WHERE IsRead='0' ";
		
		if (type != 0) {
			sqlScript += " AND Type='" + type + "'";
		}
		
		Cursor cursor = CommonDao.executeSql(sqlScript);
		count = cursor.getCount();
		
		for (int i = 0; i < count; i++) {
			listId.add(cursor.getInt(0));
			cursor.moveToNext();
		}
		cursor.close();

		return listId;
	}
	
	public static ArrayList<Integer> getAllLikeId() {
		ArrayList<Integer> listId = new ArrayList<Integer>();
		int count;
		String sqlScript = "SELECT ID FROM TBL_STORY WHERE IsLike='1' AND IsRead='0' ";

		Cursor cursor = CommonDao.executeSql(sqlScript);
		count = cursor.getCount();
		
		for (int i = 0; i < count; i++) {
			listId.add(cursor.getInt(0));
			cursor.moveToNext();
		}
		cursor.close();

		return listId;
	}
	
	public static StoryDto findById(int id) {
		StoryDto dto = new StoryDto();
		
		String sqlScript = "SELECT * FROM TBL_STORY WHERE Id='" + id + "'";
		Cursor cursor = CommonDao.executeSql(sqlScript);
		if (cursor.getCount() > 0) {
			setCursorToDto(cursor, dto);
		}
		cursor.close();
		return dto;
	}
	
	public static void update(StoryDto objNew) {
		SQLiteDatabase db = DatabaseAdapter.open();
		ContentValues values = new ContentValues();
		
		values.put("Id", objNew.getId());
		values.put("Content", objNew.getContent());
		values.put("Type", objNew.getType());
		values.put("IsLike", objNew.isIslike());
		values.put("IsRead", objNew.isIsread());
		values.put("Title", objNew.getTitle());
		values.put("TheLoai", objNew.getTheloai());

		db.update(Init_TBL_STORY.TABLE_NAME, values, Constants.COLUMN_STORY_ID + "=?",
				new String[] {Integer.toString(objNew.getId())});
	}
	
	public static void updateAllToUnread(int readType) {
		String sqlScript = "UPDATE TBL_STORY SET IsRead='0'";
		
		if (readType == ReadingActivity.READ_TYPE_TEXT) {
			sqlScript += " WHERE Type='1'";
		} else if (readType == ReadingActivity.READ_TYPE_IMAGE) {
			sqlScript += " WHERE Type='2'";
		} else if (readType == ReadingActivity.READ_TYPE_LIKE) {
			sqlScript += " WHERE IsLike='1'";
		}

		CommonDao.executeSql(sqlScript);
	}

	private static void setCursorToDto(Cursor cursor, StoryDto dto) {
		dto.setId(cursor.getInt(0));
		dto.setContent(cursor.getString(1));
		dto.setType(cursor.getInt(2));
		dto.setIslike(cursor.getInt(3) == 1);
		dto.setIsread(cursor.getInt(4) == 1);
		dto.setTitle(cursor.getString(5));
		dto.setTheloai(cursor.getString(6));

	}
}
